#!/usr/bin/python
# -*- coding: UTF-8 -*-

import re
import sys
import os
import time
import threading
import datetime
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from mpl_toolkits.mplot3d import Axes3D


#isMysql = 0
#isRedis = 0
#starttime = 0

def writefile(content, filepath, di):
    fp = open(filepath, di)
    fp.write(content)
    return fp.close()

def readfile(filepath):
    fp = open(filepath, 'r')
    fileread = fp.read()
    fp.close()
    return fileread

def runMysql():
    #os.system("sudo service mysql restart > /dev/null 2>&1")
    starttime = datetime.datetime.now()
    os.system("./exe > /dev/null 2>&1")
    os.system("./exe > /dev/null 2>&1")


    endtime = datetime.datetime.now()
    global isMysql
    isMysql = 1
    print "Mysql:" + str((endtime - starttime).total_seconds())
    #os.system("sudo service mysql restart > /dev/null 2>&1")

def runRedis():
    #os.system("redis-cli FLUSHALL")
    #os.system("sudo service redis-server restart > /dev/null 2>&1")
    #time.sleep(2)
    #starttime = datetime.datetime.now()
    for num in range(1,16000):
        os.system("redis-cli -h 127.0.0.1 -p 6379 get key%d > /dev/null 2>&1" % (random.randint(1,10000)))
        global redis_thread
        redis_thread = redis_thread + 1
#   time.sleep(10)
    endtime = datetime.datetime.now()
    global isRedis
    isRedis = 1
    print "Redis:" + str((endtime - starttime).total_seconds())
    #os.system("sudo service redis-server restart > /dev/null 2>&1")

def runHttpd():
    os.system("sudo service apache2 restart > /dev/null 2>&1")
    #starttime = datetime.datetime.now()
    os.system("ab -n 400000 -c 500 http://127.0.0.1/index.html > /dev/null 2>&1")
    endtime = datetime.datetime.now()
    print "Httpd:" + str((endtime - starttime).total_seconds())
    os.system("sudo service apache2 restart > /dev/null 2>&1")

def simple_plot(et, tm1, tr1):

    x = [1, 2, 4, 5]
    xt= [1.5, 2.5, 4.5, 5.5]
    height = [0, 0, 0, 0]
    weight = [1, 1, 1, 1]
    xlabel = ['MySQL-1st','Redis-1st', 'MySQL-2nd','Redis-2nd']

    if et==str(0):
        pl = 0
    else:
        pl = 2
        height[0] = tm1
        height[1] = tr1

    for i in range(30000):
	plt.cla()
	plt.bar(x, height, weight, color=['darkorange', 'royalblue', 'darkorange', 'royalblue'])
	plt.title("Excution Time of MySQL and Redis")
	plt.xticks(xt, xlabel )
	plt.ylim(0, 180)
	plt.xlim(1, 6)
	#plt.xlabel(height)
	for xi in range(4):
		plt.annotate('{}'.format(height[xi]),
                    xy=(xt[xi] , height[xi]),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
	
	plt.pause(0.5)
        endtime = datetime.datetime.now()
        global isMysql, isRedis
        if isMysql == 0:
	    height[pl] = float('%.1f' % (endtime - starttime).total_seconds())
        if isRedis == 0:
	    height[pl+1] = float('%.1f' % (endtime - starttime).total_seconds())
        if isMysql == 1 and isRedis == 1:
            if pl == 0:
                writefile(str(height[pl]), "MySQL-1st", "w+")
                writefile(str(height[pl+1]), "Redis-1st", "w+")
            break
	
    plt.show()
    
def simple_plot2():



    x = [1, 2, 4, 5]
    xt= [1.5, 2.5, 4.5, 5.5]
    height = [0, 0, 0, 0]
    weight = [1, 1, 1, 1]
    xlabel = ['MySQL','Redis']
    pl = 0

    last_mysql = 0
    last_redis = 0
    last_time = 0
    flag = 0

    for i in range(30000):

	cmd = "ps -ef | grep ResourceMonitor | grep -v grep"
	if flag == 0:
	    re = os.system(cmd)
	if re == 0 and flag == 0:
            flag = 1
	    mysql_thread = int(readfile("mysql-thread-num"))
            global redis_thread
	    last_mysql = mysql_thread
            last_redis = redis_thread
	    last_time = (datetime.datetime.now() - starttime).total_seconds()

	plt.cla()
	plt.bar(x, height, weight, color=['darkorange', 'royalblue', 'darkorange', 'royalblue'])
	plt.title("Average Excution_Time/Operation of MySQL and Redis")
	plt.xticks(xt, xlabel )
	plt.ylim(0, 100)
	plt.xlim(1, 6)
	#plt.xlabel(height)
	for xi in range(4):
		plt.annotate('{}'.format(height[xi]),
                    xy=(xt[xi] , height[xi]),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
	
	plt.pause(2)
        mysql_thread = int(readfile("mysql-thread-num"))
        global redis_thread

        endtime = datetime.datetime.now()
        #curtime = (endtime - last_time).total_seconds()
	runtime = (endtime - starttime).total_seconds() -last_time

        global isMysql, isRedis
        if isMysql == 0:
	    height[pl] = float('%.2f' % (runtime/max(mysql_thread-last_mysql, 1) * 100 *10))
	    print "time", str(runtime), str(mysql_thread)
        if isRedis == 0:
	    height[pl+1] = float('%.2f' % (runtime/max(redis_thread-last_redis, 1) *100 *20))

	
    plt.show()

if __name__ == '__main__':
    global isMysql, isRedis, starttime, redis_thread
    isMysql = 0
    isRedis = 0
    redis_thread = 0
    et = sys.argv[1]

    tm1 = 0
    tr1 = 0
    if et==str(1):
        tm1 = float(readfile("MySQL-1st"))
        tr1 = float(readfile("Redis-1st"))

    starttime = datetime.datetime.now()
    threadMysql = threading.Thread(target=runMysql, args=())
    threadRedis = threading.Thread(target=runRedis, args=())
    threadPlot  = threading.Thread(target=simple_plot, args=(et, tm1, tr1))
    #threadPlot2  = threading.Thread(target=simple_plot2, args=())

    threadRedis.start()
    threadMysql.start()
    threadPlot.start()
    #threadPlot2.start()
    
    threadMysql.join()
    threadRedis.join()
    threadPlot.join()
    #threadPlot2.join()
